import {
	mapState
} from 'vuex'
import {
	setColumnsSearchInfo,
	getColumnsSearchInfo
} from '@/utils/base'
import QS from 'qs';

import {
	loadingJs
} from '@/utils/tools/load.js';
// 注入全局minix
export default {
	computed: {
		...mapState({
			isAdmin: state => state.user.isAdmin,
			isSchoolMaster: state => state.user.isSchoolMaster,
			isMangAdmin: state => state.user.isMangAdmin,
			globalOrgId: state => state.globalOrg && state.globalOrg.orgId,
			eventlist: state => state.websockStore.eventlist,
			userinfo: (state) => state.user.userinfo,
		}),
		/* eventlist() {
			return this.$store.getters.onEvent('answer');
		}, */
		basefileUrl() {
			return process.env.VUE_APP_FILE_API
		},
		wsUrl() {
			return process.env.VUE_APP_WS_API
		},

	}
}
export const rowSelection = {
	data() {
		return {
			selectedRowKeys: [],
		}
	},
	computed: {

	},
	watch: {
		globalOrgId(newValue, oldValue) {
			this.$nextTick(() => {
				this.$refs.protable && this.$refs.protable.handlerRefresh();
			});
		}
	},
	created() {

	},
	methods: {
		/* 选中checkbox */
		onSelectChange(selectedRowKeys) {
			this.selectedRowKeys = selectedRowKeys;
			const selectedRowChange = this.$listeners['selectedRowChange'];
			if (selectedRowChange && typeof selectedRowChange === 'function') {
				selectedRowChange(selectedRowKeys);
			}
		},
		//获取选择行数据
		getSelectedRow(list, rowKey) {
			let selectedRow = [];
			selectedRow = list.filter(item => {
				if (this.selectedRowKeys.indexOf(item[rowKey]) > -1) {
					return item;
				}
			})
			return selectedRow
		}

	}
};




var answerCount = 0;
let seq = 0; //序号
var studentIndex = -1;
var studentName = "";
var studentClass = "";
//学生的姓名班级需要全部配置时 所有学生信息的json集合
var jsonArr = [];
//var uuidSet = [];//答题器ID数组
var answerCountArray = new Array();
var fileByteArray = [];
var answerFileByteArray = [];
//升级文件
var file = "";
var answerFile = "";
var md5String = "";
var answerMd5String = "";
var length = 0;
var answerLength = 0;



var intToByteArray = function(number, length) {
	let bytes = [];
	let i = length;
	do {
		bytes[--i] = number & 255;
		number = number >> 8;
	} while (i);
	return bytes;
};


var stringToBytes = function(str) {
	var bytes = [];
	for (var i = 0; i < str.length; i++) {
		var charCode = str.charCodeAt(i);
		bytes.push(charCode);
	}
	return bytes;
}


function bitsToBytes(bits) {
	var bytes = [];
	for (var i = 0; i < bits.length; i += 8) {
		var byteBits = bits.slice(i, i + 8);
		var byte = 0;
		for (var j = 0; j < byteBits.length; j++) {
			byte = (byte << 1) | byteBits[j];
		}
		bytes.push(byte);
	}
	return bytes;
}

var isChineseCharacter = function(str) {
	var reg = /^[\u4e00-\u9fa5]+$/;
	return reg.test(str);
}


var getCharData = function(str) {
	var byteList = Array()
	for (let index = 0; index < str.length; index++) {
		const char = str[index];
		var data = getCharBytes(char);
		data.forEach(it => {
			byteList.push(it);
		});
	}
	return byteList;
}
/*有线接收器*/
export const DQTMixins = {
	data() {
		return {
			consoleList: [], //控制台
			uuidSet: [], //答题器ID数组
		}
	},
	created() {
		//将Vue方法传到全局对象window中
		window.send = this.send;
		window.handlerResult = this.handlerResult;
		window.seq = seq;

		window.intToByteArray = intToByteArray;
		window.stringToBytes = stringToBytes;
		window.bitsToBytes = bitsToBytes;
		window.intToByteArray = intToByteArray;
		window.isChineseCharacter = isChineseCharacter;
		window.getCharData = getCharData;


	},
	mounted() {
		console.log("hshhdhhd>>>>>>>>>>>>>>>>>>")
		//loadingCss('/static/demo/css/xxx.css');
		function callback() {
			loadingJs('/DQT/DQT_Data.js');
			loadingJs('/DQT/DQT_SDK.js');
			loadingJs('/DQT/DQT_Utils.js');
			loadingJs('/DQT/hzk16Utils.js');
			loadingJs('/DQT/encodeToGb2312.js');
		}
		callback()
		/* loadingJs('/static/DQT/HT44_RP522D_Data.js',callback).then(()=>{
			//你的初始化代码
		  }); */




		/* loadingJs('/static/DQT/HT44_RP522D_Data.js').then(()=>{
		}) */
		/* loadJs('/DQT/HT44_RP552D_SDK.js').then(()=>{
		})
		loadJs('/DQT/HT44_RP552D_Utils.js').then(()=>{
		}) */
	},
	methods: {
		send(type) {
			switch (type) {
				case 1:
					var json = {
						"fun": "get_dev_info"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 2:
					var json = {
						"fun": "rf_ch_set",
						"ch": 6,
						"tx_power": 3
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 3:
					var json = {
						"fun": "clear_wl",
						"uID": []
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 4:
					console.log(Date.now());
					answerCount = 0;
					answerCountArray.length = 0;
					var questions = selectQuestion(selectQuestionIndex)
					var json = {
						"fun": "answer_start",
						"questions": questions,
						"auto": 0
					};
					this.addJsonListItem(JSON.stringify(json));
					console.log(Date.now());
					sendData(json)
					break;
				case 5:
					var json = {
						"fun": "answer_stop"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 6:
					var json = {
						"fun": "connect_devices"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 7:
					var json = {
						"fun": "pw_set",
						"pw": 12
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 8:
					answerCount = 0;
					answerCountArray.length = 0;
					//发送家庭作业
					//在线作答
					var questions = [{
							type: "s",
							id: "1",
							range: "A-D"
						},
						{
							type: "m",
							id: "2",
							range: "A-F"
						},
						{
							type: "j",
							id: "3",
							range: ""
						},
						{
							type: "d",
							id: "4",
							range: "1-9999"
						},
						{
							type: "g",
							id: "5",
							range: ""
						},
						{
							type: "v",
							id: "6",
							range: ""
						},
						{
							type: "e",
							id: "7",
							range: "0-100"
						},
					];
					switch (selectHomeworkCountIndex) {
						case "1":
							//七道题型
							//七道 题型时，无须处理 每种题型各一道就可以
							break;
						case "2":
							//30道题型
							for (let index = 0; index < 23; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "3":
							//60道题型
							for (let index = 0; index < 53; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "4":
							//90道题型
							for (let index = 0; index < 83; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "5":
							//120道题型
							for (let index = 0; index < 113; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						default:
							break;
					}
					var json = {
						"fun": "homework_start",
						"sub": selectHomeworkSubjectIndex,
						"questions": questions
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 9:
					var json = {
						"fun": "answer_stop"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 10:
					//发送收取家庭作业指令
					var json = {
						"fun": "homework_update_start",
						"sub": selectHomeworkSubjectIndex
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 11:
					var signIn = getSignInCheckBoxValue();
					if (signIn) {
						var json = {
							"fun": "sign_in_start"
						};
						this.addJsonListItem(JSON.stringify(json));
						sendData(json)
					} else {
						var json = {
							"fun": "sign_in_stop"
						};
						this.addJsonListItem(JSON.stringify(json));
						sendData(json)
					}
					break;
				case 12:
					var json = {
						"fun": "read_card_start"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 13:
					var json = {
						"fun": "read_card_stop"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 14:
					var json = {
						"fun": "hand_wireless_bind_start"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 15:
					var json = {
						"fun": "auto_wireless_bind_start",
						"list": []
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 16:
					var checked = getCheckBoxValue();
					if (checked) {
						var json = {
							"fun": "raise_hand_start"
						};
						this.addJsonListItem(JSON.stringify(json));
						sendData(json)
					} else {
						var json = {
							"fun": "raise_hand_stop"
						};
						this.addJsonListItem(JSON.stringify(json));
						sendData(json)
					}
					break;
				case 17:
					var json = {
						"fun": "name_start",
						"uID": 2444793094,
						"name": "张三",
						"className": "一班"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 18:
					var json = {
						"fun": "name_stop"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 19:
					//套题测试
					answerCount = 0;
					answerCountArray.length = 0;
					//套题目测试
					var questions = [{
							type: "s",
							id: "1-1",
							range: "A-D"
						},
						{
							type: "m",
							id: "1-2",
							range: "A-F"
						},
						{
							type: "j",
							id: "1-3",
							range: ""
						},
						{
							type: "d",
							id: "1-4",
							range: "1-9999"
						},
						{
							type: "g",
							id: "2-1",
							range: ""
						},
						{
							type: "v",
							id: "2-2",
							range: ""
						},
						{
							type: "e",
							id: "2-3",
							range: "0-100"
						},
					];
					var json = {
						"fun": "answer_start",
						"questions": questions,
						"auto": 0
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 20:
					console.log(Date.now());
					answerCount = 0;
					answerCountArray.length = 0;
					var questions = [{
							type: "s",
							id: "1",
							range: "A-D"
						},
						{
							type: "m",
							id: "2",
							range: "A-F"
						},
						{
							type: "j",
							id: "3",
							range: ""
						},
						{
							type: "d",
							id: "4",
							range: "1-9999"
						},
						{
							type: "g",
							id: "5",
							range: ""
						},
						{
							type: "v",
							id: "6",
							range: ""
						},
						{
							type: "e",
							id: "7",
							range: "0-100"
						},
					]
					switch (selectMuQuestionIndex) {
						case "1":
							//七道题型
							//七道 题型时，无须处理 每种题型各一道就可以
							break;
						case "2":
							//30道题型
							for (let index = 0; index < 23; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "3":
							//60道题型
							for (let index = 0; index < 53; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "4":
							//90道题型
							for (let index = 0; index < 83; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						case "5":
							//120道题型
							for (let index = 0; index < 113; index++) {
								var randomNumber = Math.floor(Math.random() * 8);
								questions.push(createQuestion(randomNumber, 8 + index));
							}
							break;
						default:
							break;
					}
					var value = getAutoAnswerCheckBoxValue();
					var json = {
						"fun": "answer_start",
						"questions": questions,
						"auto": value
					};
					this.addJsonListItem(JSON.stringify(json));
					console.log(Date.now());
					sendData(json)
					break;
				case 21:
					//给答题器配置姓名和班级信息
					if (studentIndex == -1) {
						//全部配置

						for (let index = 0; index < this.uuidSet.length; index++) {
							var uuid = this.uuidSet[index].uuid;
							var name = this.uuidSet[index].name;
							var className = this.uuidSet[index].className;
							var json = {
								"fun": "name_start",
								"uID": uuid,
								"name": name,
								"className": className
							};
							jsonArr[index] = json;
						}
						this.addJsonListItem(JSON.stringify(jsonArr[0]));
						sendData(jsonArr[0]);
					} else {
						//仅配置选中的索引的那个学生
						var uuid = this.uuidSet[studentIndex - 1].uuid;
						var name = "";
						var className = "";
						if (studentName == null) {
							name = this.uuidSet[studentIndex].name;
						} else {
							name = studentName;
						}
						if (studentClass == null) {
							className = this.uuidSet[studentIndex].className;
						} else {
							className = studentClass;
						}
						var json = {
							"fun": "name_start",
							"uID": uuid,
							"name": name,
							"className": className
						};
						this.addJsonListItem(JSON.stringify(json));
						sendData(json);
					}
					break;
				case 22:
					//给所有学生 统一配置姓名和班级
					if (studentName != null || studentClass != null) {
						for (let index = 0; index < this.uuidSet.length; index++) {
							if (studentName != null) {
								this.uuidSet[index].name = studentName.concat(index.toString());
								changListItem(index + 1, 3, studentName.concat(index.toString()))
							}
							if (studentClass != null) {
								this.uuidSet[index].className = studentClass;
								changListItem(index + 1, 4, studentClass)
							}
						}
					}
					break;
				case 23:
					//停止绑定
					var json = {
						"fun": "wireless_bind_stop"
					};
					this.addJsonListItem(JSON.stringify(json));
					sendData(json)
					break;
				case 24:
					//接收器升级
					var json = {
						fun: "send_update_file_message",
						"file": file,
						"md5": md5String,
						"fileLength": length
					};
					sendData(json)
					this.addJsonListItem(JSON.stringify(json));
					break;
				case 25:
					//发送开始无线升级指令
					var json = {
						"fun": "send_answer_upgrade",
						file: answerFile,
						answerLength: answerLength,
						answerMd5String: answerMd5String
					};
					sendData(json)
					this.addJsonListItem(JSON.stringify(json));
					break;
				case 26:
					//停止无线升级指令
					var json = {
						"fun": "stop_answer_upgrade"
					};
					sendData(json)
					this.addJsonListItem(JSON.stringify(json));
					break;
				default:
					break;
			}
		},

		//控制台日志,更新日志
		addJsonListItem(json) {
			console.log(JSON.stringify(json))
			this.consoleList.push({
				time: moment().format('YYYY-MM-DD HH:mm:ss'),
				json: json
			})
		},
		//处理结果
		handlerResult(data) {

			console.log("调用了吗？" + JSON.stringify(data))
			this.addJsonListItem(JSON.stringify(data));
			// 处理结果数据
			if (data.fun == "get_dev_info") {
				var uuid = ""
				if (data.ports[0].list.length != 0) {
					for (let index = 0; index < data.ports[0].list.length; index++) {
						const uuidItem = data.ports[0].list[index].uID;

						var containsUuid = false;
						for (let index = 0; index < this.uuidSet.length; index++) {
							const element = this.uuidSet[index];
							if (element.uuid == uuidItem) {
								containsUuid = true;
							}
						}
						if (!containsUuid) {
							this.uuidSet.push({
								"uuid": uuidItem,
								"rssi": "",
								"name": "",
								"className": "",
								"setState": "unConfig",
								"bindNumber": "0",
								"handNumber": "0",
								"singNumber": "0",
								"answerNumber": "0",
								"equipmentFinsh": "0",
								"equipmentContent": "",
								"upgradeProgress": ""
							});
							var json = this.uuidSet[this.uuidSet.length - 1];
							addListItem(json, this.uuidSet.length);
						}
						uuid = uuid + "uuid:" + uuidItem + "  ";
					}
				}
				var json = "返回设备信息result:  软件版本:" + data.version + " 硬件版本：" + data.hardware_version +
					" 公司名称：" + data.comname + " 发送信道:" + data.sendPort + " 接收信道:" + data.acceptPort + " 射频功率:" +
					data
					.tx_power +
					" 2.4G考勤协议:" + data.rf_ch + " 白名单：" + uuid;
				this.addJsonListItem(json)
			} else if (data.fun == "ch_set") {
				var json = (data.result == 0 ? "设置射频信道成功" : "设置射频信道失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "pw_set") {
				var json = (data.result == 0 ? "设置射频功率成功" : "设置射频功率失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "answer_start") {
				var json = (data.result == 0 ? "题目下发成功" : "题目下发失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "answer_stop") {
				var json = (data.result == 0 ? "停止作答下发成功" : "停止作答下发失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "clear_wl") {
				var json = (data.result == 0 ? "全部清空白名单成功" : "全部清空白名单失败");
				// this.addJsonListItem(json);
				this.removeListItem();
			} else if (data.fun == "raise_hand_start") {
				var json = (data.result == 0 ? "设置允许举手成功" : "设置允许举手失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "raise_hand_stop") {
				var json = (data.result == 0 ? "设置禁止举手成功" : "设置禁止举手失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "raise_hand_update") {
				var json = data.time + "  uuid:" + data.uuid + "  rssi:" + data.signalStrength;
				var json = (data.result == 1 ? json + "   举手成功" : json + "    举手失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "sign_in_update") {
				var json = data.time + "  uuid:" + data.uuid + "  rssi:" + data.signalStrength;
				var json = (data.result == 1 ? json + "   签到成功" : json + "    签到失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "read_card_start") {
				var json = (data.result == 0 ? "开始读取卡号成功" : "    发送开始读取卡号失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "read_card_stop") {
				var json = (data.result == 0 ? "发送停止读取卡号成功" : "    发送停止读取卡号失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "hand_wireless_bind_start") {
				if (data.bindCode == 0) {
					var json = (data.result == 0 ? "发送自动绑定成功" : "    发送自动绑定失败");
					for (let index = 0; index < this.uuidSet.length; index++) {
						let uuid = this.uuidSet[index];
						let studentInfo = {}
						let isHasuIDIndex = this.studentList.findIndex(item => item.machineId == uuid)
						console.log("学生isHasuIDIndex：》》》》" + JSON.stringify(isHasuIDIndex))
						console.log("学生名单：》》》》" + JSON.stringify(this.studentList))
						if (isHasuIDIndex == -1) {
							studentInfo = this.studentList[index]
							console.log("一个学生信息" + JSON.stringify(studentInfo))
							var json = {
								"fun": "name_start",
								"uID": uuid,
								"name": studentInfo.studName,
								"className": studentInfo.className
							};

							this.studentList[index].machineId = uuid;
							console.log("学生名单：》》》》" + JSON.stringify(this.studentList))

							sendData(json);


						}

						//var uuid = this.uuidSet[index].uuid;
						// var name = this.uuidSet[index].name;
						// var className = this.uuidSet[index].className;

						//jsonArr[index] = json;


					}


					// this.addJsonListItem(json);
				} else {
					var json = (data.result == 0 ? "发送手动绑定成功" + "  绑定码：" + data.bindCode : "    发送手动绑定失败");
					// this.addJsonListItem(json);
				}
			} else if (data.fun == "wireless_bind_stop") {
				var json = (data.result == 0 ? "发送停止绑定成功" : "    发送停止绑定失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "card_update") {
				let isHasuIDIndex = this.uuidSet.findIndex(uID => uID == data.uID)
				if (isHasuIDIndex == -1) {
					this.uuidSet.push(data.uID)
				}

				console.log("答题器ID数组" + JSON.stringify(this.uuidSet))
				var json = ("刷卡返回卡号：" + data.uID);
				//调用自动绑定功能
				var json = {
					"fun": "auto_wireless_bind_start",
					"list": [data.uID]
				};
				sendData(json);
				// this.addJsonListItem(json);
			} else if (data.fun == "update_wireless_card") {
				var json = ("反馈绑定的答题器UUID:" + data.uuid + "被替换的UUID:" + data.releaseuuid);
				// this.addJsonListItem(json);
				var containsUuid = false;
				for (let index = 0; index < this.uuidSet.length; index++) {
					const element = this.uuidSet[index];
					if (element.uuid == data.uuid) {
						containsUuid = true;
					}
				}
				if (!containsUuid) {
					this.uuidSet.push({
						"uuid": data.uuid,
						"rssi": "",
						"name": "",
						"className": "",
						"setState": "unConfig",
						"bindNumber": "0",
						"handNumber": "0",
						"singNumber": "0",
						"answerNumber": "0",
						"equipmentFinsh": "0",
						"equipmentContent": "",
						"upgradeProgress": ""
					});
					var json = this.uuidSet[this.uuidSet.length - 1];
					this.addListItem(json, this.uuidSet.length);
				}
			} else if (data.fun == "sign_in_start") {
				var json = (data.result == 0 ? "设置允许签到成功" : "    设置允许签到失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "sign_in_stop") {
				var json = (data.result == 0 ? "设置禁止签到成功" : "    设置禁止签到失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "answer_update") {
				console.log("dddd" + Date.now());
				var answerJson = data.answer;
				var tempS = "";
				var allAnswer = "";
				for (let index = 0; index < answerJson.length; index++) {
					const element = JSON.stringify(answerJson[index]);
					tempS = (tempS + element);
					if (answerJson[index].answer != 0 && answerJson[index].answer != null) {
						allAnswer = allAnswer.concat("[").concat(answerJson[index].answer).concat("]");
					}
				}
				var containsUuid = false;
				var saveIndex = -1;
				for (let index = 0; index < this.uuidSet.length; index++) {
					const element = this.uuidSet[index];
					if (element.uuid == data.uuid) {
						containsUuid = true;
						saveIndex = index;
					}
				}
				if (containsUuid && saveIndex != -1 && !answerCountArray.includes(data.uuid)) {
					this.uuidSet[saveIndex].rssi = data.rssi;
					this.uuidSet[saveIndex].equipmentContent = this.uuidSet[saveIndex].equipmentContent.concat(",")
						.concat(allAnswer);
					this.changListItem(saveIndex + 1, 2, data.rssi);
					this.changListItem(saveIndex + 1, 11, allAnswer);
				}
				if (!answerCountArray.includes(data.uuid)) {
					answerCountArray.push(data.uuid);
					answerCount = answerCountArray.length;
					showAnswerCount.textContent = answerCount;
					// var json = (data.time + "   答题器 UUID:" + data.uuid + "当前集合长度：" + answerCountArray.length);
					// this.addJsonListItem(json);
				}

			} else if (data.fun == "chinese_stop") {
				var json = (data.result == 0 ? "发送停止配置姓名指令成功" : "    发送停止配置姓名指令失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "chinese_start") {
				var json = (data.result == 0 ? "发送配置姓名指令成功" : "    发送配置姓名指令失败");
				// this.addJsonListItem(json);
			} else if (data.fun == "homework_update") {
				var answerJson = data.answer;
				var tempS = ""
				for (let index = 0; index < answerJson.length; index++) {
					const element = JSON.stringify(answerJson[index]);
					tempS = (tempS + element);
				}
				var json = (data.time + "   答题器 UUID:" + data.uuid + "  信号强度:" + data.rssi + "   收取作业答案:" + tempS);
				// this.addJsonListItem(json);
			} else if (data.fun == "name_update") {
				//修改配置状态
				var containsUuid = false;
				var saveIndex = -1;
				for (let index = 0; index < this.uuidSet.length; index++) {
					const element = this.uuidSet[index];
					if (element.uuid == data.uuid) {
						containsUuid = true;
						saveIndex = index;
					}
				}
				if (containsUuid && saveIndex != -1) {
					this.uuidSet[saveIndex].setState = "Config Ok";
					this.changListItem(saveIndex + 1, 5, "Config Ok");
				}
				for (let index = 0; index < jsonArr.length; index++) {
					if (jsonArr[index].uID == data.uuid) {
						jsonArr.splice(index, 1);
						break;
					};

				}
				if (jsonArr.length != 0) {
					sendData(jsonArr[0]);
				}
				// var json = ("   答题器 UUID:" + data.uuid + "姓名班级配置成功");
				// this.addJsonListItem(json);
			} else if (data.fun == "jsq_pnp_event") {
				var json = "";
				if (data.event == "connected") {
					json = "检测到552D接收器插入";
				} else {
					json = "检测到552D接收器拔出";
				}
				// addJsonListItem(json);
			} else if (data.fun == "stop_answer_upgrade") {
				var json = "";
				if (data.result == 0) {
					json = "发送停止无线升级指令成功";
				} else {
					json = "发送停止无线升级指令失败";
				}
				this.removeListItem();
				// this.addJsonListItem(json);
			} else if (data.fun == "progress") {
				var containsUuid = false;
				var listIndex = -1;
				for (let index = 0; index < this.uuidSet.length; index++) {
					const element = this.uuidSet[index];
					if (element.uuid == data.uID) {
						containsUuid = true;
						listIndex = index;
					}
				}
				if (!containsUuid) {
					this.uuidSet.push({
						"uuid": data.uID,
						"rssi": "",
						"name": "",
						"className": "",
						"setState": "unConfig",
						"bindNumber": "0",
						"handNumber": "0",
						"singNumber": "0",
						"answerNumber": "0",
						"equipmentFinsh": "0",
						"equipmentContent": "",
						"upgradeProgress": data.pro
					});
					var json = this.uuidSet[this.uuidSet.length - 1];
					this.addListItem(json, this.uuidSet.length);
				} else {
					this.changListItem(listIndex + 1, 12, data.pro);
				}
			} else if (data.fun == "recieveProgress") {
				receiverProgress.textContent = data.pro;
			}
		},



		//清除白名单
		removeListItem() {
			/* var myList = document.getElementById("myList");
			for (let index = myList.children.length - 1; index > 0; index--) {
			  var ul = myList.getElementsByTagName("ul")[index];
			  myList.removeChild(ul);
			}
			this.uuidSet.splice(0, this.uuidSet.length); */
		},

		changListItem(index, indexItem, changeText) {
			/* var fifthUl = document.getElementById("myList").getElementsByTagName("ul")[index];
			var thirdLi = fifthUl.getElementsByTagName("li")[indexItem];
			thirdLi.innerHTML = changeText; */
		},

		addListItem(json, number) {
			/* var myList = document.getElementById("myList");
		  var listItem = document.createElement("ul");
		  listItem.setAttribute("id", "list_item");
		  listItem.setAttribute("style", "display: flex; flex-direction: row; width: 100% ;list-style-type: none;");
		
		  var li1 = document.createElement("li");
		  li1.setAttribute("id", "equipment_serial_number");
		  li1.style.width = "80px"
		  li1.innerHTML = number;
		
		  var li2 = document.createElement("li");
		  li2.setAttribute("id", "equipment_uid");
		  li2.style.width = "160px"
		  li2.innerHTML = json.uuid;
		
		  var li3 = document.createElement("li");
		  li3.setAttribute("id", "equipment_rssi");
		  li3.style.width = "80px"
		  li3.innerHTML = json.rssi;
		
		  var li4 = document.createElement("li");
		  li4.setAttribute("id", "equipment_name");
		  li4.style.width = "80px"
		  li4.innerHTML = json.name;
		
		  var li5 = document.createElement("li");
		  li5.setAttribute("id", "equipment_class");
		  li5.style.width = "80px"
		  li5.innerHTML = json.className;
		
		  var li6 = document.createElement("li");
		  li6.setAttribute("id", "equipment_set_state");
		  li6.style.width = "100px"
		  li6.innerHTML = json.setState;
		
		  var li7 = document.createElement("li");
		  li7.setAttribute("id", "equipment_bind_number");
		  li7.style.width = "80px"
		  li7.innerHTML = json.bindNumber;
		
		  var li8 = document.createElement("li");
		  li8.setAttribute("id", "equipment_hand_number");
		  li8.style.width = "80px"
		  li8.innerHTML = json.handNumber;
		
		  var li9 = document.createElement("li");
		  li9.setAttribute("id", "equipment_sign_number");
		  li9.style.width = "80px"
		  li9.innerHTML = json.singNumber;
		
		  var li10 = document.createElement("li");
		  li10.setAttribute("id", "equipment_sign_answer_number");
		  li10.style.width = "80px"
		  li10.innerHTML = json.answerNumber;
		
		  var li11 = document.createElement("li");
		  li11.setAttribute("id", "equipment_finsh");
		  li11.style.width = "80px"
		  li11.innerHTML = json.equipmentFinsh;
		
		  var li12 = document.createElement("li");
		  li12.setAttribute("id", "equipment_content");
		  li12.style.width = "380px"
		  li12.innerHTML = json.equipmentContent;
		
		  var li13 = document.createElement("li");
		  li13.setAttribute("id", "upgrade_progress");
		  li13.style.width = "80px"
		  li13.innerHTML = json.upgradeProgress;
		
		
		  listItem.appendChild(li1);
		  listItem.appendChild(li2);
		  listItem.appendChild(li3);
		  listItem.appendChild(li4);
		  listItem.appendChild(li5);
		  listItem.appendChild(li6);
		  listItem.appendChild(li7);
		  listItem.appendChild(li8);
		  listItem.appendChild(li9);
		  listItem.appendChild(li10);
		  listItem.appendChild(li11);
		  listItem.appendChild(li12);
		  listItem.appendChild(li13);
		
		  myList.appendChild(listItem);
		  listItem.addEventListener("click", function () {
		    if (json.name != null) {
		      student_name.value = json.name;
		    }
		    if (json.className != null) {
		      student_class.value = json.className;
		    }
		  }) */
		},
	}

};



import md5 from 'md5';
//列表的增删改查
export const recordOperation = {
	data() {
		return {
			checkpassword:''
		}
	},
	methods: {
		/* 刷新列表当前页 */
		handlerRefresh(type) {
			this.$refs.protable.handlerRefresh(type);
		},
		/* 新增 */
		addRecord() {
			this.$refs.addOrEditModal.add();
		},
		/* 编辑 */
		editRecord(record) {
			this.$refs.addOrEditModal.edit(record);
		},
		/* 查看 */
		viewRecord(record, api) {
			this.$refs.detailModal.show(record, api);
		},
		/* 导入 */
		importRecord() {
			this.$refs.uploadModal.show();
		},
		/*导出*/
		/* exportRecord(delIds) {
			this.$postAction(this.api.export, delIds).then(res => {
				if (res && res.code == 1) {
					this.$message.success('导出成功！');
					this.handlerRefresh();
				}
			});
		}, */
		/* 确认是否删除 */
		showDeleteConfirm(type, delId, name) {
			let _this = this;
			let title, ids;
			if (type == 0) {
				title = '你确定删除选中的' + this.selectedRowKeys.length + '条数据吗？';
				ids = this.selectedRowKeys.map(item => item);
			} else {
				title = ( <div> 你确定要删除 <span style = "color:red;" > {
					name ? '(' + name + ')' : ''
				} </span>吗 ?</div> );
				ids = [delId];
			}
			
			if(this.userinfo.delVerify){
				this.checkpassword='';
				this.$confirm({
					title:title,
					content: (h) => (
						<a-form autocomplete="off">
							<a-form-item label="删除后信息将不能恢复" help="删除需要校验密码，如不需要请在基础数据-其他设置中取消">
								<a-input type="password" placeholder="请输入校验密码" v-model={this.checkpassword} />
							</a-form-item>
						</a-form>
					),
					okText: '确定',
					cancelText: '取消',
					class: 'confirmbox',
					okType: 'danger',
					onOk: async () => {
						await this.delVerify(this.checkpassword, ids);
					},
					onCancel() {},
				});
			}else{
			this.$confirm({
				title: title,
				content:'删除后信息将不能恢复' ,
				okText: '确定',
				cancelText: '取消',
				class: 'confirmbox',
				okType: 'danger',
				onOk() {
					_this.removeRecord(ids);
				},
				onCancel() {}
			});
			}
		},
		/* 校验密码 */
		delVerify(checkpassword, delIds) {
			return new Promise((resolve, reject) => {
				if(!checkpassword){
					this.$message.error('请输入校验密码');
					reject();
				}
				else{
				let md5Pass = md5(checkpassword.trim());
				this.$postAction(this.$api.delVerify, {
					md5Pass,
					password: checkpassword,
					userId: this.userinfo.userId,
				}).then((res) => {
					if (res && res.code == 1 && res.data == 1) {
						this.removeRecord(delIds);
						resolve();
					} else {
						this.$message.error('密码错误，请重新输入密码');
						reject();
					}
				});
				}
			});
		},
		/*删除*/
		removeRecord(delIds) {
			this.$postAction(this.api.delete, delIds).then(res => {
				if (res && res.code == 1) {
					this.$message.success('删除成功！');
					this.handlerRefresh();
				}
			});
		},
		setColumnsSearchInfo,
		getColumnsSearchInfo,
		//获取筛选条件并更新表格列
		getFilterDefaultValue() {
			let filterparam = this.$refs.protable.$refs.filterbars.getFilterDefaultValue();
			console.log('操作的条件' + JSON.stringify(filterparam));
			let columns = JSON.parse(JSON.stringify(this.columns));
			columns.forEach(item => {
				for (var key in filterparam) {
					if (item.searchInfo) {
						//这里分两种情况有时候添加了筛选条件没有设置value值，就用dataIndex判断，并赋值默认值(原始defaultValue!=新的筛选默认值时)
						if ((item.searchInfo.value && item.searchInfo.value == key) || (!item.searchInfo
								.value && item.dataIndex == key)) {
							if (item.searchInfo.defaultValue != filterparam[key]) {
								item.searchInfo.defaultValue = filterparam[key];
							}
						}
					}
				}
			});
			this.columns = [...columns];
			console.log('获取筛选条件并更新表格列' + JSON.stringify(this.columns));
		},


	}
};
export const tableResize = {
	data() {
		return {
			scrolly: 500,
			viewlistTop: 0,
			filterbarHeight: 72

		}
	},
	mounted() {
		if (this.$refs.filterbar) {
			this.filterbarHeight = this.$refs.filterbar.offsetHeight;
		}
	},
	methods: {
		onResize(resize) {
			let marginTop = 10;
			let tableHeader = 44;
			let tableFooter = 80;
			this.scrolly = resize.height - tableHeader - tableFooter;
			if (this.$refs.filterbar) {
				this.filterbarHeight = this.$refs.filterbar.offsetHeight;
			}
		}
	}
};
/* 弹出框的公共设置 */
export const ModalMixins = {
	data() {
		return {
			labelCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 5
				}
			},
			wrapperCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 16
				}
			},
			visible: false,
			confirmLoading: false,
			mdl: {},
			form: this.$form.createForm(this),
			title: '新增',
			isAdd: true
		}
	},
	props: {
		//接口地址
		api: {
			type: Object,
			default: () => {}
		},
		//标题
		modalTitle: {
			type: String,
			default: ''
		},
		//编辑的唯一标识
		editKey: {
			type: String,
			default: ''
		}
	},
	methods: {
		/** 
		 * @description  输入转换成大写
		 * @param {Object} value
		 */
		normalizeUp(value) {
			return value ? value.toUpperCase() : '';
		},
		/**
		 * @description  清除输入框中的空格
		 * @param {Object} e change事件的参数
		 */
		removeSpaces(e) {
			return e.target.value.trim();
			// return e.target.value.replace("\\u200B","")
		},
		//下拉框筛选
		filterOption(input, option) {
			return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
		},
		add(record) {
			this.isAdd = true;
			this.initInfo(record);
		},
		edit(record) {
			this.isAdd = false;
			this.initInfo(record);
		},
		initInfo(record = {}) {
			this.mdl = Object.assign({}, record);
			this.title = (this.isAdd ? '新增' : '编辑') + this.modalTitle;
			this.visible = true;
			//获取一些初始下拉数据
			this.getDefaultList && this.getDefaultList();
			this.$nextTick(() => {
				this.form.resetFields();
				this.setFieldsValue()
			});
		},
		/**
		 * 数据的回填
		 */
		setFieldsValue() {
			if (!this.isAdd) {
				/* 如果有编辑回填方法，嗲用编辑回填，否则调用默认方法 */
				if (this.setEditFieldsValue && typeof this.setEditFieldsValue === 'function') {
					this.setEditFieldsValue()
				} else {
					/* 先获取所有的item 然后赋值 */
					let list = Object.keys(this.form.getFieldsValue());
					// console.log("list", list);
					let fieldNames = list.filter(item => item != 'orgId')
					// console.log('this.$pick(this.mdl, ...fieldNames)', this.$pick(this.mdl, ...fieldNames))
					this.form.setFieldsValue(this.$pick(this.mdl, ...fieldNames));
					if (this.isAdmin && list.includes('orgId')) {
						this.form.setFieldsValue({
							orgId: this.mdl.orgId
						});
					}
				}

			} else if (this.setAddFieldsValue) {
				/* 如果有新增默认数据 回填新增默认数据 */
				typeof this.setAddFieldsValue === 'function' && this.setAddFieldsValue()
			}
		},

		/**
		 * 点击确认按钮
		 */
		handleOk() {
			// 触发表单验证
			this.form.validateFields((err, values) => {
				console.log("Coder", values);
				// 验证表单没错误
				if (!err) {
					/* 处理地址 */
					let id = this.mdl[this.editKey];
					let parameter = Object.assign({}, values, id ? {
						[this.editKey]: id
					} : '');
					this.saveInfo(this.isAdd ? this.api.add : this.api.edit, parameter);
				}
			});
		},
		/**
		 * 关闭弹出
		 */
		handleCancel() {
			this.confirmLoading = false;
			this.$emit('close');
			this.visible = false;
		},
		//保存数据
		saveInfo(url, parames) {
			this.confirmLoading = true;
			this.$postAction(url, parames)
				.then(res => {
					console.log(res);
					if (res && res.code == 1) {
						this.$message.success('保存成功');
						this.$emit('ok');
						this.form.resetFields();
						this.visible = false;
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
	}
};